package com.thudojsc.canvasengine.util;

import java.util.ArrayList;

public abstract class GenericPool<T> {
	private final ArrayList<T> mAvailableItems;
	
	public GenericPool() {
		mAvailableItems = new ArrayList<T>();
	}
	
	public synchronized int getAvailableItemCount() {
		return mAvailableItems.size();
	}
	
	protected abstract T onAllocatePoolItem();
	
	protected void onHandleObtain(final T pItem) {
		
	}
	
	protected void onHandleRecycle(final T pItem) {
		
	}
	
	public synchronized T obtain() {
		final T item;
		
		final int available_item_size = mAvailableItems.size();
		
		if (available_item_size > 0) {
			item = mAvailableItems.remove(available_item_size - 1);
		} else {
			item = onAllocatePoolItem();
		}
		
		onHandleObtain(item);
		return item;
	}
	
	public synchronized void recycle(final T pItem) {
		onHandleRecycle(pItem);
		mAvailableItems.add(pItem);
	}
}
